//
//  UICurveView.m
//  NTempure
//
//  Created by longkin on 15/1/31.
//  Copyright (c) 2015年 elsonic.inc. All rights reserved.
//

#import "UICurveView.h"

#define KChartLeftPadding 25
#define KChartBottomPadding 35
#define KChartTopPadding 25
#define KChartRightPadding 25
#define KLineWidth 0.5
#define KLineColor @"#e1e1e1"
#define KHWidth 32.5//单元格宽度
#define KVWidth 12.5//单元格高度

@implementation UICurveView

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        font = [UIFont systemFontOfSize:9];
        
        zeroPoint = CGPointMake(KChartLeftPadding, frame.size.height - KChartBottomPadding);
        _textStyleDict = [NSDictionary dictionaryWithObjectsAndKeys:
                          font,NSFontAttributeName,
                          [UIColor ColorFromHtml:@"#9d9d9d"], NSForegroundColorAttributeName, nil];
        
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCurve:)];
        [self addGestureRecognizer:tap];
        
        longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressed:)];
        longPress.minimumPressDuration = 1;
        [self addGestureRecognizer:longPress];
        
    }
    return self;
}

/*单击切换曲线*/
-(void)tapCurve:(UITapGestureRecognizer *)gesture{
    
    
}

/*长按操作选中曲线*/
-(void)onLongPressed:(UILongPressGestureRecognizer *)gesture{
    
    CGPoint point = [gesture locationInView:self];
    if(self.curveItems.count > 0){
        //判断长按区域
        CurveModel *model = [self.curveItems objectAtIndex:self.curveItems.count - 1];//最后一个曲线区域在最前端
        CGMutablePathRef path = CGPathCreateMutable();
        CGPoint lastpoint;
        CGPathMoveToPoint(path, nil, zeroPoint.x + KLineWidth, zeroPoint.y - KLineWidth);
        for (NSValue *value in model.hourtempures) {
            NSInteger hour = [value hourTempureValue].hour;
            CGFloat tempure = [value hourTempureValue].tempure;
            
            CGFloat x = hour * KHWidth + KLineWidth;
            CGFloat y = 7 * KVWidth/35 * tempure + KLineWidth;
            CGPathAddLineToPoint(path, NULL, x, y);
            
            lastpoint = CGPointMake(x, y);
        }
        CGPathAddLineToPoint(path, NULL,lastpoint.x, zeroPoint.y - KLineWidth);
        if (CGPathContainsPoint(path, NULL, point, NO)) {
            if ([self.delegate respondsToSelector:@selector(curveView:longPressed:)]) {
                [self.delegate curveView:self longPressed:model];
            }
        }
        CGPathRelease(path);
    }
    
}

-(void)setXChartBlock:(ChartBlock)xChartBlock
{
    _xChartBlock = xChartBlock;
    [self setNeedsDisplay];
}

-(void)setYChartBlock:(ChartBlock)yChartBlock
{
    _yChartBlock = yChartBlock;
    [self setNeedsDisplay];
}

-(void)setCurveItems:(NSArray *)curveItems
{
    _curveItems = curveItems;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    //[self drawCoordinateXY];
    
    [self drawGrid];
    [self drawNumbers];
    
    [self drawCurves2];
}


// 通过coreGraphics画坐标轴
-(void)drawCoordinateXY
{
    CGFloat xCoordinateWidth = self.xChartBlock.width * self.xChartBlock.count;
    //CGFloat yCoordinateHeight = self.yChartBlock.width * self.yChartBlock.count;
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGMutablePathRef xPath = CGPathCreateMutable();
    CGPathMoveToPoint(xPath, nil, KChartLeftPadding, self.bounds.size.height - KLineWidth - KChartBottomPadding);
    CGPathAddLineToPoint(xPath, nil, KChartLeftPadding + xCoordinateWidth + 2 - KChartRightPadding, self.bounds.size.height - KLineWidth - KChartBottomPadding);
    CGContextSetLineWidth(ctx, KLineWidth);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    [[UIColor ColorFromHtml:KLineColor] set];
    CGContextAddPath(ctx, xPath);
    CGContextDrawPath(ctx, kCGPathStroke);
    CGPathRelease(xPath);
    
    CGMutablePathRef yPath = CGPathCreateMutable();
    CGPathMoveToPoint(yPath, nil, KChartLeftPadding, self.bounds.size.height - KLineWidth - KChartBottomPadding);
    CGPathAddLineToPoint(yPath, nil, KChartLeftPadding, KChartTopPadding);
    CGContextAddPath(ctx, yPath);
    CGContextDrawPath(ctx, kCGPathStroke);
    CGPathRelease(yPath);
    
}

//绘制网格
-(void)drawGrid
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(ctx, KLineWidth);
    CGContextSetLineCap(ctx, kCGLineCapButt);
    [[UIColor ColorFromHtml:KLineColor] setStroke];
    CGContextSetShouldAntialias(ctx, NO);//消除锯齿
    
    //画网格竖线
    for (int i = 0; i < 9; i++) {
        CGFloat x = zeroPoint.x + i*KHWidth;
        CGFloat y = zeroPoint.y - 8*KVWidth;
        
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, nil, x, zeroPoint.y);
        CGPathAddLineToPoint(path, nil, x, y);
        CGContextAddPath(ctx, path);
        CGContextDrawPath(ctx, kCGPathStroke);
        CGPathRelease(path);
    }
    
    //画横线
    for (int i = 0; i < 8; i++) {
        CGFloat y = zeroPoint.y - i * KVWidth;
        
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, nil, zeroPoint.x, y);
        CGPathAddLineToPoint(path, nil, zeroPoint.x + 9 * (KHWidth + KLineWidth) - 15, y);
        CGContextAddPath(ctx, path);
        CGContextDrawPath(ctx, kCGPathStroke);
        CGPathRelease(path);
    }
}


//绘制坐标刻度
-(void)drawNumbers
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetShouldAntialias(ctx, YES);
    [[UIColor ColorFromHtml:@"#9d9d9d"] set];
    
    NSInteger num = 0;
    for (int i = 0; i < 8 ; i++) {
        //绘制标数
        num = i*3;
        CGFloat x = zeroPoint.x + i*KHWidth;
        NSString *numstr = [NSString stringWithFormat:@"%ld",num];
        CGSize txtsize = [numstr sizeWithFont:font];

        [numstr drawAtPoint:CGPointMake(x - txtsize.width/2, zeroPoint.y) withFont:font];
    }
    
    NSString *h = @"h";
    [h drawAtPoint:CGPointMake(zeroPoint.x + 8*KHWidth + 6, zeroPoint.y) withFont:font];
    
    num = 0;
    for (int i = 0; i < 8; i++) {
        if (i == 0) {
            continue;
        }
        //绘制标数
        num = i*5;
        
        CGFloat y = zeroPoint.y - i*KVWidth;
        NSString *numstr = [NSString stringWithFormat:@"%ld",num];
        CGSize txtsize = [numstr sizeWithFont:font];

        [numstr drawAtPoint:CGPointMake(zeroPoint.x - txtsize.width - 2, y - txtsize.height / 2) withFont:font];
    }
    
    NSString *c = @"℃";
    [c drawAtPoint:CGPointMake(zeroPoint.x - 14, zeroPoint.y - 7*KVWidth - 18) withFont:font];
  
}

//绘制多条曲线
-(void)drawCurves2{

    for (CurveModel *model in self.curveItems) {
        
        //1。转化hourtempure为坐标
        NSArray *hourtemps = model.hourtempures;
        
        NSMutableArray *points = [[NSMutableArray alloc] init];
        for (NSValue *value in hourtemps) {
            
            NSInteger hour = [value hourTempureValue].hour;
            CGFloat tempure = [value hourTempureValue].tempure;
            NSLog(@"hour %ld, tempure:%f",hour,tempure);
            
            CGFloat x = hour * KHWidth + KLineWidth;
            CGFloat y = 7 * KVWidth/35 * tempure + KLineWidth;
            
            
            [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x + x,zeroPoint.y - y)]];
        }
        
        [model.lineColor set];
        
        UIBezierPath *funcLinePath = [UIBezierPath bezierPath];
        CGPoint point = [[points firstObject] CGPointValue];
        [funcLinePath moveToPoint:point];
        [funcLinePath setLineCapStyle:kCGLineCapRound];
        [funcLinePath setLineJoinStyle:kCGLineJoinRound];

        for (NSValue *pointValue in points) {
            point = [pointValue CGPointValue];
            NSLog(@"x %f, y %f",point.x,point.y);
            [funcLinePath addLineToPoint:point];
            [funcLinePath moveToPoint:point];
            [funcLinePath stroke];
        }
        
        //填充折现区域
        CGContextRef context = UIGraphicsGetCurrentContext();
        [model.fillColor setFill];
        //从原点开始
        CGContextMoveToPoint(context, zeroPoint.x + KLineWidth, zeroPoint.y - KLineWidth);
        for (NSValue *pointValue in points) {
            CGContextAddLineToPoint(context, [pointValue CGPointValue].x, [pointValue CGPointValue].y);
        }
        NSValue *lastvalue = [points lastObject];
        //结束点
        CGContextAddLineToPoint(context, [lastvalue CGPointValue].x, zeroPoint.y - KLineWidth);
        CGContextFillPath(context);
        
    }
    
    //绘制提示文本

    NSString *tip = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_CURVE_PROMPT];

    [[UIColor whiteColor] setFill];
    [tip drawAtPoint:CGPointMake(zeroPoint.x + 20, zeroPoint.y - 40) withFont:[UIFont boldSystemFontOfSize:12]];

}

//绘制曲线
-(void)drawCurves{
    
    //UIColor *color = [UIColor ColorFromHtml:@"#faa4c9"];
    [[UIColor clearColor] set];
    
    NSMutableArray *points = [[NSMutableArray alloc] init];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+0.5,zeroPoint.y-14)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+1*KHWidth,zeroPoint.y-20)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+2*KHWidth,zeroPoint.y-60)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+3*KHWidth,zeroPoint.y-40)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+4*KHWidth,zeroPoint.y-70)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+5*KHWidth,zeroPoint.y-64)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+6*KHWidth,zeroPoint.y-78)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+7*KHWidth,zeroPoint.y-48)]];
    [points addObject:[NSValue valueWithCGPoint:CGPointMake(zeroPoint.x+8*KHWidth,zeroPoint.y-80)]];
    
    //===========
    UIBezierPath *strokeLinePath = [UIBezierPath bezierPath];
    CGPoint point = [[points firstObject] CGPointValue];
    [strokeLinePath moveToPoint:point];
    [strokeLinePath setLineCapStyle:kCGLineCapRound];
    [strokeLinePath setLineJoinStyle:kCGLineJoinRound];
    int index = 0;
    for (NSValue *pointValue in points) {
        point = [pointValue CGPointValue];
        [strokeLinePath addLineToPoint:point];
        [strokeLinePath moveToPoint:point];
        [strokeLinePath stroke];
        index++;
    }
    
    //===========
    /*
    CAShapeLayer *lineLayer = [self setUpLineLayer];
    lineLayer.path = strokeLinePath.CGPath;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 1.5;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    pathAnimation.autoreverses = NO;
    [lineLayer addAnimation:pathAnimation forKey:@"lineLayerAnimation"];
    
    lineLayer.strokeEnd = 1.0;
    [self.layer addSublayer:lineLayer];
    */
    
    //填充折现区域
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[[UIColor ColorFromHtml:@"#faa4c9"] colorWithAlphaComponent:0.5] setFill];
    //从原点开始
    CGContextMoveToPoint(context, zeroPoint.x + 0.5, zeroPoint.y - 0.5);
    for (NSValue *pointValue in points) {
        CGContextAddLineToPoint(context, [pointValue CGPointValue].x, [pointValue CGPointValue].y);
    }
    NSValue *lastvalue = [points lastObject];
    //结束点
    CGContextAddLineToPoint(context, [lastvalue CGPointValue].x, zeroPoint.y - 0.5);
    CGContextFillPath(context);

}

-(CAShapeLayer *)setUpLineLayer
{
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    lineLayer.lineCap = kCALineCapRound;
    lineLayer.lineJoin = kCALineJoinBevel;
    lineLayer.strokeEnd = 0.0;
    lineLayer.strokeColor = [UIColor ColorFromHtml:@"#faa4c9"].CGColor;
    lineLayer.lineWidth = 1;
    return lineLayer;
}


@end

/************************************************************************************/
//XYValue
@implementation NSValue(HourTempureValue)

+(NSValue *)valueWithHourTempure:(HourTempureValue)hourtemp
{
    NSValue *value = [NSValue valueWithBytes:&hourtemp objCType:@encode(HourTempureValue)];
    return value;
}

-(HourTempureValue)hourTempureValue{
    HourTempureValue hr;
    [self getValue:&hr];
    return hr;
}

@end



/************************************************************************************/
@implementation CurveModel

-(void)setHourtempures:(NSArray *)hourtempures{
    _hourtempures = hourtempures;
}

-(NSArray *)points
{
    return _points;
}

- (NSComparisonResult)compareCurve:(CurveModel *)model{
    
    if ([model.name isEqualToString:self.name]) {
        return NSOrderedAscending;
    }
    return NSOrderedDescending;
}

@end

